<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="regionType">
        <el-select v-model="queryParams.regionType" placeholder="请选择地区" clearable>
          <el-option label="省" value="province" />
          <el-option label="市" value="city" />
          <el-option label="区县" value="district" />
          <el-option label="乡镇" value="township" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['nongjt:region:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['nongjt:region:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="regionList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :default-expand-all="false"
      :expand-row-keys="expandedKeys"
      @expand-change="handleExpandChange"
      lazy
      :load="loadChildren"
      style="width: 100%">
      <el-table-column label="名称" prop="name" min-width="200" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
          <i v-if="scope.row.hasChildren" 
             :class="scope.row.expanded ? 'el-icon-minus' : 'el-icon-plus'" 
             style="margin-left: 8px; cursor: pointer;"
             @click="toggleExpand(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column label="简称" align="center" prop="shortName" min-width="120" />
      <el-table-column label="区域代码" align="center" prop="regionCode" min-width="120" />
      <el-table-column label="经度" align="center" prop="longitude" min-width="120" />
      <el-table-column label="纬度" align="center" prop="latitude" min-width="120" />
      <el-table-column label="排序" align="center" prop="sortOrder" min-width="80" />
      <el-table-column label="状态" align="center" prop="status" min-width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == '0'" type="success">正常</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.regionType !== 'township'"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAddChild(scope.row)"
            v-hasPermi="['nongjt:region:add']"
          >添加子节点</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['nongjt:region:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['nongjt:region:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改区域管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item v-if="form.parentId" label="上级区域" prop="parentName">
          <el-input v-model="form.parentName" :disabled="true" />
        </el-form-item>
        <el-form-item label="区域代码" prop="regionCode">
          <el-input v-model="form.regionCode" placeholder="请输入区域代码" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入简称" />
        </el-form-item>
        <el-form-item label="区域划分" prop="regionType">
          <el-select v-model="form.regionType" placeholder="请选择区域划分">
            <el-option label="省" value="province" />
            <el-option label="市" value="city" />
            <el-option label="区县" value="district" />
            <el-option label="乡镇" value="township" />
          </el-select>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRegion, getRootRegions, getChildrenRegions, getRegion, delRegion, delRegionRecursively, addRegion, updateRegion } from "@/api/monitor/njt/region/index";

export default {
  name: "Region",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 区域管理表格数据
      regionList: [],
      // 展开的行
      expandedKeys: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        name: null,
        status: null,
        regionType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        regionCode: [
          { required: true, message: "区域代码不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        shortName: [
          { required: true, message: "简称不能为空", trigger: "blur" }
        ],
        regionType: [
          { required: true, message: "区域划分不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询区域管理列表 */
    getList() {
      this.loading = true;
      getRootRegions().then(response => {
        this.regionList = response.data;
        this.loading = false;
      });
    },
    /** 展开/收起节点 */
    toggleExpand(row) {
      if (row.expanded) {
        // 收起节点
        this.expandedKeys = this.expandedKeys.filter(key => key !== row.id);
        row.expanded = false;
        // 清空子节点
        this.clearChildren(row);
      } else {
        // 展开节点
        this.expandedKeys.push(row.id);
        row.expanded = true;
        // 加载子节点
        this.loadChildren(row);
      }
    },
    /** 加载子节点 */
    loadChildren(row) {
      if (row.children && row.children.length > 0) {
        return; // 已经加载过了
      }
      getChildrenRegions(row.id).then(response => {
        this.$set(row, 'children', response.data);
      });
    },
    /** 清空子节点 */
    clearChildren(row) {
      this.$set(row, 'children', []);
    },
    /** 懒加载子节点 */
    loadChildren(tree, treeNode, resolve) {
      getChildrenRegions(tree.id).then(response => {
        resolve(response.data);
      });
    },
    /** 展开变化处理 */
    handleExpandChange(row, expandedRows) {
      if (expandedRows.includes(row)) {
        this.loadChildren(row);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        regionCode: null,
        name: null,
        shortName: null,
        regionType: null,
        longitude: null,
        latitude: null,
        sortOrder: 0,
        status: "0",
        parentId: null,
        parentName: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加区域管理";
    },
    /** 添加子节点操作 */
    handleAddChild(row) {
      this.reset();
      this.form.parentId = row.id;
      this.form.parentName = row.name;
      // 根据父级类型设置子级类型
      if (row.regionType === 'province') {
        this.form.regionType = 'city';
      } else if (row.regionType === 'city') {
        this.form.regionType = 'district';
      } else if (row.regionType === 'district') {
        this.form.regionType = 'township';
      }
      this.open = true;
      this.title = "添加子节点";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRegion(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改区域管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRegion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      const name = row.name;
      this.$modal.confirm('是否确认删除"' + name + '"及其所有子节点？删除后将无法恢复！').then(function() {
        return delRegionRecursively(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('nongjt/region/export', {
        ...this.queryParams
      }, `区域管理_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.el-table .el-table__row {
  cursor: pointer;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}

.el-icon-plus,
.el-icon-minus {
  color: #409eff;
  font-size: 14px;
}

.el-icon-plus:hover,
.el-icon-minus:hover {
  color: #66b1ff;
}
</style>
